package com.wgj.android.tools;

import android.annotation.TargetApi;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.accessibility.AccessibilityNodeInfo;

import com.jiaai.xui.utils.log.XLog;

/**
 * Created by Administrator on 2017/11/2.
 */

public class AccessibilityServerTools  {

    /**
     * 递归查找可以点击的节点并模拟点击
     * @param node
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    public static void performActionClick(final AccessibilityNodeInfo node) {
        if (node.isEnabled()) {
             node.performAction(AccessibilityNodeInfo.ACTION_CLICK);
        } else {
             performActionClick(node.getParent());
        }
    }

    /**
     * 模拟输入
     * @param context
     * @param inputNodeInfo
     * @param content
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    public static void performActionInput(Context context, AccessibilityNodeInfo inputNodeInfo,String content) {
        if(inputNodeInfo!=null){
            Bundle arguments = new Bundle();
            arguments.putInt(AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT,
                    AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD);
            arguments.putBoolean(AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN,
                    true);
            inputNodeInfo.performAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY,
                    arguments);
            inputNodeInfo.performAction(AccessibilityNodeInfo.ACTION_FOCUS);
            ClipData clip = ClipData.newPlainText("label", content);
            ClipboardManager clipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            clipboardManager.setPrimaryClip(clip);
            inputNodeInfo.performAction(AccessibilityNodeInfo.ACTION_PASTE);
        }
    }

    /**
     *递归查找窗口匹配文本的节点
     * @param node
     * @param s
     * @return
     */
    public  static  AccessibilityNodeInfo findNodeByText(AccessibilityNodeInfo node,String s) {
        if (node.getChildCount() == 0) {
            if (node.getText() != null) {
                if (s.equals(node.getText().toString())) {
                    return node;
                }
            }
        } else {
            for (int i = 0; i < node.getChildCount(); i++) {
                if (node.getChild(i) != null) {
                    findNodeByText(node.getChild(i),s);
                }
            }
        }
        return node;

    }


}
